package com.zheng.shop.admin.controller.other;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zheng.common.base.BaseController;
import com.zheng.common.util.CamelUnderlineConverter;
import com.zheng.common.util.RedisUtil;
import com.zheng.common.validator.LengthValidator;
import com.zheng.common.validator.NotNullValidator;
import com.zheng.shop.common.constant.ShopResult;
import com.zheng.shop.common.constant.ShopResultConstant;
import com.zheng.shop.common.exception.ShopException;
import com.zheng.shop.dao.model.ShopDict;
import com.zheng.shop.rpc.api.ShopDictService;
import com.zheng.upms.common.constant.UpmsConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: xinqi
 * Date: 2017/11/16
 * Time: 11:17
 */
@Controller
@Api(value = "数据字典管理", description = "数据字典管理")
@RequestMapping("/manage/product/dict")
public class DictController extends BaseController {
    @Autowired
    private ShopDictService dictService;

    @ApiOperation(value = "数据字典首页")
    @RequiresPermissions("product:dict:read")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        return "/manage/other/dict/index.jsp";
    }

    @ApiOperation(value = "商品分类列表")
    @RequiresPermissions("product:dict:read")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(@RequestParam(required = false, defaultValue = "1", value = "pageNumber") int pageNumber,
                       @RequestParam(required = false, defaultValue = "10", value = "pageSize") int pageSize,
                       @RequestParam(required = false, defaultValue = "", value = "searchText") String searchText,
                       @RequestParam(required = false, value = "sortName") String sortName,
                       @RequestParam(required = false, value = "sortOrder") String sortOrder) {
        Wrapper<ShopDict> wrapper = new EntityWrapper<>();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            if (sortOrder.equalsIgnoreCase("asc")) {
                wrapper = wrapper.orderBy(CamelUnderlineConverter.camel2underline(sortName), true);
            } else {
                wrapper = wrapper.orderBy(CamelUnderlineConverter.camel2underline(sortName), false);
            }
        }
        if (StringUtils.isNotBlank(searchText)) {
            wrapper.like("`key`", searchText);
        }
        wrapper.groupBy("`key`");
        Page<ShopDict> page = dictService.selectPage(new Page<>(pageNumber, pageSize), wrapper);
        int total = dictService.selectDictCount(searchText);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", page.getRecords());
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "新增数据字典")
    @RequiresPermissions("product:dict:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create() {
        return "/manage/other/dict/create.jsp";
    }

    @ApiOperation(value = "新增数据字典")
    @RequiresPermissions("product:dict:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(@RequestBody String dicts) {
        try {
            dictService.createDict(dicts);
        } catch (ShopException e) {
            return new ShopResult(ShopResultConstant.FAILED, e.getMessage());
        }
        return new ShopResult(ShopResultConstant.SUCCESS, ShopResultConstant.SUCCESS.getCode());
    }

    @ApiOperation(value = "修改数据字典")
    @RequiresPermissions("product:dict:update")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String update(@PathVariable("id") Integer id, Model model) {
        ShopDict dict = dictService.selectById(id);
        String key = dict.getKey();
        EntityWrapper<ShopDict> dictEntityWrapper = new EntityWrapper<>();
        dictEntityWrapper.where("`key`='" + key + "'");
        List<ShopDict> dictList = dictService.selectList(dictEntityWrapper);
        model.addAttribute("dictList", dictList);
        return "/manage/other/dict/update.jsp";
    }

    @ApiOperation(value = "修改数据字典")
    @RequiresPermissions("product:dict:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@RequestBody JSONObject params) {
        JSONArray dictList = params.getJSONArray("dictList");
        List<ShopDict> shopDictList = dictList.toJavaList(ShopDict.class);
        String oldKey = params.getString("oldKey");
        try {
            dictService.updateDict(shopDictList, oldKey);
        } catch (ShopException e) {
            return new ShopResult(ShopResultConstant.FAILED, e.getMessage());
        }
        return new ShopResult(ShopResultConstant.SUCCESS, ShopResultConstant.SUCCESS.getCode());
    }

    @ApiOperation(value = "删除数据字典")
    @RequiresPermissions("product:dict:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Object delete(@RequestBody List<Integer> ids) {
        try {
            dictService.deleteBatchDict(ids);
        } catch (ShopException e) {
            return new ShopResult(ShopResultConstant.FAILED, e.getMessage());
        }
        return new ShopResult(ShopResultConstant.SUCCESS, ShopResultConstant.SUCCESS.getCode());
    }
}
